// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

const db = cloud.database();

exports.main = async (event, context) => {
  const foodId = event.foodId;
  const foodName=event.foodName;
  const foodPrice=event.foodPrice;
  const foodUrl=event.foodUrl;
  const number=1;
  const openId= event.openId
  // 查询数据库中是否存在该记录
  try {
    const res = await db.collection('shop').where({
      openId: openId,
      foodId: foodId
    }).get();

    if (res.data.length === 0) {
      // 如果不存在，添加新记录
      await db.collection('shop').add({
        data:{
          foodId: foodId,
        foodName: foodName, // 确保 shop 对象有 foodName 属性
        foodPrice: foodPrice,
        foodUrl: foodUrl,
        openId: openId,
        number: number,
        selected:"0"
        }
      });
      return {
        success: true,
        message: '加入成功'
      };
    } else {
      // 如果存在，更新 number 字段
      await db.collection('shop').where({
        openId: openId,
        foodId: foodId
      }).update({
        data: {
          number: res.data[0].number + 1
        }
      });
      return {
        success: true,
        message: '更新成功'
      };
    }
  } catch (e) {
    console.error('数据库操作失败:', e);
    return {
      success: false,
      message: '操作失败'
    };
  }
};